<script setup lang="ts">
import { Message } from '@arco-design/web-vue'
import dayjs from 'dayjs'
import {
  addCertRenewApi,
  getCertApi,
  getCertRecordApi,
  getCertRecordBaseApi,
} from '@/apis/modules/cert'
import {
  certListStatusOptions,
  certManualApplyOptions,
  LicenseSourceOptions,
} from '@/constants/cdn-node'
import { commonTableProps } from '@/utils/table'
import ApplyLog from './dialogs/ApplyLog.vue'
import CertDownload from './dialogs/CertDownload.vue'
import EditorDialog from './dialogs/EditorDialog.vue'
import useConfig from './useConfig'

const route = useRoute()

const { tableColumns, searchSchema } = useConfig()

const queryParams = ref({ cert_id: route.params.id })

let pollingInterval: ReturnType<typeof setInterval> | null = null
const POLLING_INTERVAL_TIME = 5000

// 停止轮询
function stopPolling() {
  if (pollingInterval) {
    clearInterval(pollingInterval)
    pollingInterval = null
  }
}

const {
  loading,
  data: tableData,
  pagination,
  run,
} = useListRequest(getCertRecordBaseApi, {
  params: queryParams,
  immediate: true,
  afterFn: (res) => {
    if (res && res.length > 0) {
      if (res[0].status === 3) {
        startPolling(res[0])
      }
    }
  },
})

function getCertRecord(record: any) {
  getCertRecordApi({ id: record.id })
    .then((res) => {
      if (res.status === 2 || res.status === 1) {
        stopPolling()
        tableData.value[0] = res
        if (res.status === 1) {
          const id = ref(route.params.id)
          getCertDetail(id.value)
        }
      }
      // formState.value = res
    })
    .catch(() => {
      stopPolling()
    })
}
// 开始轮询
function startPolling(record: any) {
  const fetchWithId = () => getCertRecord(record)
  fetchWithId()
  pollingInterval = setInterval(fetchWithId, POLLING_INTERVAL_TIME)
}

const {
  visible: editorDialogVisible,
  open: openEditorDialog,
  data: editorDialogData,
} = usePopup()

const {
  visible: detailVisible,
  open: openDetail,
  data: detailData,
} = usePopup()

const { visible: logVisible, open: openLog, data: logData } = usePopup()
// 删除
// function handleDelete(id: string) {
//   ModalHelper.error({
//     title: '删除证书',
//     content: '确定要删除该证书么？该记录将从列表中移除。',
//     okText: '删除',
//     width: 480,
//     closable: false,
//     onOk: async () => {
//       await deleteSwitcherApi({ id })
//       await run()
//       Message.success('删除成功')
//     },
//   })
// }

const formState = ref({
  id: '',
  created_at: '',
  updated_at: '',
  domain: '',
  brand: '',
  source: 0,
  auto_renew: true,
  expired_at: '',
  crt: '',
  private_key: '',
})

// 更新证书
function UpdateCertificate(id: string) {
  console.log(tableData)
  if (tableData && tableData.value[0].status === 3) {
    ModalHelper.confirm({
      title: '更新证书',
      content: '证书更新中，请稍后。',
      okText: '确定',
      width: 480,
      hideCancel: true,
      closable: false,
      onOk: async () => {
        // await addCertRenewApi({ id })
        await run()
        // Message.success('操作成功')
      },
    })
  } else {
    ModalHelper.confirm({
      title: '更新证书',
      content: '更新后会直接替换云资源的旧证书，确定更新吗？',
      okText: '确定',
      width: 480,
      closable: false,
      onOk: async () => {
        await addCertRenewApi({ id })
        await run()
        Message.success('操作成功')
      },
    })
  }
}

// let timer: NodeJS.Timer

// const clear = watch(
//   () => isEnd.value,
//   (val) => {
//     if (val) {
//       clearInterval(timer)
//       clear()
//     }
//   },
// )
// watchEffect(() => {
//   if (visible.value && !isEnd.value) {
//     pollMessage()
//   } else {
//     clearInterval(timer)
//     clear()
//   }
// })

async function handleOpenLog(record: LicenseListItem) {
  // const res = await getSwitcherListApi(record.id!)
  openLog(record)
  // if (res)
  //   openLog(record)
}

/** 获取详情基础信息 */
function getCertDetail(id: string) {
  getCertApi({ id }).then((res) => {
    formState.value = res
  })
}

const domainList = computed(() => {
  return formState.value.domain ? formState.value.domain.split(',') : []
})

function openDownloadDetail() {
  if (!Number(formState.value.expired_at))
    return Message.error('没有可下载证书')
  detailData.value = formState.value
  openDetail(detailData.value)
}

onMounted(() => {
  const id = ref(route.params.id)
  getCertDetail(id.value)
})

onUnmounted(() => {
  stopPolling()
})
</script>

<template>
  <main-container
    v-model:pagination="pagination"
    :loading="loading"
    @run="run"
  >
    <!-- <div class="mb-4 flex">
      <multiple-condition-search
        v-model="queryParams"
        :schema="searchSchema"
        @search="run"
      />
    </div> -->
    <div class="detail-container">
      <div class="detail-domain">
        <div class="detail-domain-title">
          域名
        </div>
        <div class="detail-domain-value">
          <div
            v-for="(item, index) in domainList"
            :key="index"
            class="detail-domain-value-item"
          >
            {{ item }}
            <a-divider
              v-if="index !== domainList.length - 1"
              direction="vertical"
            />
          </div>
        </div>
      </div>
      <a-divider
        :size="1"
        style="border-bottom-style: dashed"
        margin="0"
      />
      <div class="detail-domain-box">
        <div class="detail-domain-item">
          <div class="detail-item-title">
            所属应用
          </div>
          <div class="detail-item-value">
            {{ formState.brand || '-' }}
          </div>
        </div>
        <div class="detail-domain-item">
          <div class="detail-item-title">
            证书品牌
          </div>
          <div class="detail-item-value">
            {{ formState.brand || '-' }}
          </div>
        </div>
        <div class="detail-domain-item">
          <div class="detail-item-title">
            证书来源
          </div>
          <div class="detail-item-value">
            {{ getOptionsLabel(LicenseSourceOptions, formState.source) }}
          </div>
        </div>
        <div class="detail-domain-item">
          <div class="detail-item-title">
            验证模式
            <!-- 如果手动上传 没有 如果自动就是cname -->
          </div>
          <div class="detail-item-value">
            <span v-if="formState.source === 1"> - </span>
            <span
              v-else
              class="cursor-pointer text-primary/6"
              type="primary"
              @click="openEditorDialog(formState)"
            >
              CNAME 代理验证
            </span>
          </div>
        </div>
      </div>
      <div class="detail-domain-box">
        <div class="detail-domain-item">
          <div class="detail-item-title">
            自动续签
          </div>
          <div class="detail-item-value">
            <div v-if="formState.source === 1">
              不支持
            </div>
            <div v-else>
              {{ formState.auto_renew ? '已开启' : '已关闭' }}
            </div>
          </div>
        </div>
        <div class="detail-domain-item">
          <div class="detail-item-title">
            创建时间
          </div>
          <div class="detail-item-value">
            {{
              dayjs(formState.created_at * 1000).format('YYYY-MM-DD HH:mm:ss')
            }}
          </div>
        </div>
        <div class="detail-domain-item">
          <div class="detail-item-title">
            过期时间
          </div>
          <div class="detail-item-value">
            <span v-if="formState.expired_at !== '0'">{{
              dayjs(formState.expired_at * 1000).format('YYYY-MM-DD HH:mm:ss')
            }}</span>
            <span v-else>-</span>

            <span v-if="formState?.expired_at === '0'" />
            <span
              v-else
              class="ml-2"
            >
              <span
                v-if="calculateRemainingDays(formState?.expired_at || 0) > 0"
                class="text-#86909C"
              >({{
                calculateRemainingDays(formState?.expired_at || 0)
              }}天后过期)</span>
              <span
                v-if="calculateRemainingDays(formState?.expired_at || 0) < 0"
                class="text-#FA5566"
              >(已过期)</span>
            </span>
          </div>
        </div>
        <div class="detail-domain-item" />
      </div>
    </div>
    <div class="mt-6 flex items-center justify-center">
      <div class="table-cert-title">
        更新记录
      </div>
      <div class="flex-1" />
      <div>
        <div class="flex space-x-4">
          <a-button
            v-if="formState.source !== 1"
            type="primary"
            @click="UpdateCertificate(route.params.id)"
          >
            更新证书
          </a-button>

          <a-button
            class="download-btn"
            type="outline"
            @click="openDownloadDetail"
          >
            下载证书
          </a-button>
        </div>
      </div>
    </div>
    <a-table
      class="mt-4"
      v-bind="commonTableProps"
      :columns="tableColumns"
      :data="tableData"
    >
      <template #trigger_source="{ record }">
        <div>
          <span>{{
            getOptionsLabel(certManualApplyOptions, record.trigger_source)
          }}</span>
        </div>
      </template>
      <template #status="{ record }">
        <div>
          <span
            :class="
              record?.status === 1
                ? 'text-#1D2129'
                : record?.status === 2
                  ? 'text-#FA5566'
                  : 'text-#00A65B'
            "
          >{{ getOptionsLabel(certListStatusOptions, record?.status) }}</span>
        </div>
      </template>
      <template #actions="{ record }">
        <a-link
          :hoverable="false"
          @click="handleOpenLog(record)"
        >
          <i-icons-log size="16px" />
        </a-link>
      </template>
    </a-table>
  </main-container>

  <editor-dialog
    v-if="editorDialogVisible"
    v-model:visible="editorDialogVisible"
    :record="editorDialogData"
    @refresh="run"
  />
  <cert-download
    v-model:visible="detailVisible"
    :record="detailData"
    @refresh="run"
  />
  <apply-log
    v-model:visible="logVisible"
    v-model:record="logData"
    @refresh-row="row => handleRefreshRow(row)"
  />
</template>

<style scoped lang="less">
.detail-container {
  display: flex;
  padding: 24px 16px;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  gap: 24px;
  align-self: stretch;
  border-radius: var(--border-radius-lg, 8px);
  border: 1px solid var(--border-1, #f2f3f5);
  background: #fff;

  .detail-domain {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
    align-self: stretch;

    .detail-domain-title {
      color: var(--text-3, #86909c);

      /* regular/12 */
      font-family: 'Microsoft YaHei UI';
      font-size: 12px;
      font-style: normal;
      font-weight: 400;
      line-height: normal;
    }

    .detail-domain-value {
      display: flex;
      align-items: center;
      align-content: center;
      gap: 2px;
      align-self: stretch;
      flex-wrap: wrap;

      .detail-domain-value-item {
        color: var(--text-1, #1d2129);

        /* bold/12 */
        font-family: 'Microsoft YaHei UI';
        font-size: 12px;
        font-style: normal;
        font-weight: 700;
        line-height: normal;
      }
    }
  }

  .detail-domain-box {
    display: flex;
    align-items: center;
    gap: 16px;
    align-self: stretch;

    .detail-domain-item {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      gap: 8px;
      flex: 1 0 0;

      .detail-item-title {
        color: var(--text-3, #86909c);

        /* regular/12 */
        font-family: 'Microsoft YaHei UI';
        font-size: 12px;
        font-style: normal;
        font-weight: 400;
        line-height: normal;
      }

      .detail-item-value {
        color: var(--text-1, #1d2129);

        /* regular/12 */
        font-family: 'Microsoft YaHei UI';
        font-size: 12px;
        font-style: normal;
        font-weight: 400;
        line-height: normal;
      }
    }
  }
}

.table-cert-title {
  color: var(--text-1, #1d2129);

  /* bold/14 */
  font-family: 'Microsoft YaHei UI';
  font-size: 14px;
  font-style: normal;
  font-weight: 700;
  line-height: 20px;
  /* 142.857% */
}

.download-btn {
  &:hover {
    background-color: #f2f3f5 !important;
  }
}
</style>
